/*
 *	Board.cpp
 *
 *	Created on 3/1/2011 by Alan Mattila
 */


#include "Board.h"

using std::ostream;
using std::endl;

/*********************************************************
 * Board::Board()
 ********************************************************/
Board::Board()
:player1Count(0),player2Count(0)
{
	// Allocate the memory for the game board
	InitiailizeBoard();
}

Board::Board(Board* copyBoard)
{
	InitiailizeBoard();
	(*this) = (*copyBoard);
}

void Board::InitiailizeBoard()
{
	board = new int*[BOARD_Y];
	for(unsigned i=0; i<BOARD_Y; i++)
	{
		board[i] = new int[BOARD_X];
	}
	
	// Set all of the array vales to 0
	for(unsigned i=0; i<BOARD_Y; i++)
	{
		for(unsigned j=0; j<BOARD_X; j++)
		{
			board[j][i] = CHECKERS_EMPTY;
		}
	}
}

/*********************************************************
 * Board::~Board()
 ********************************************************/
Board::~Board()
{
	if(board)
	{
		for(unsigned i=0; i<BOARD_Y; i++)
		{
			delete [] board[i];
		}
		delete [] board;
	}
}


/*********************************************************
 * Board::GetValue()
 ********************************************************/
int Board::GetValue(int x, int y) const
{
	return board[y][x];
}


/*********************************************************
 * Board::SetValue()
 ********************************************************/
void Board::SetValue(int x, int y, int value)
{
	int currentValue = GetValue(x,y);

	// Decrement the current count
	if( currentValue == CHECKERS_PLAYER1 ||
		currentValue == CHECKERS_PLAYER1_KING)
	{
		player1Count--;
	}
	else if(currentValue == CHECKERS_PLAYER2 ||
			currentValue == CHECKERS_PLAYER2_KING)
	{
		player2Count--;
	}

	// Increment for new value if needed
	if( value == CHECKERS_PLAYER1 ||
		value == CHECKERS_PLAYER1_KING)
	{
		player1Count++;
	}
	else if(value == CHECKERS_PLAYER2 ||
			value == CHECKERS_PLAYER2_KING)
	{
		player2Count++;
	}


	board[y][x] = value;
}


/*********************************************************
 * Board::operator<<()
 * Overloads the output operator so that a board can
 * easily be printed using cout.
 ********************************************************/
ostream& operator<<(ostream &os, Board &obj)
{
	os << "Player 1 Count: " << obj.GetPlayer1PieceCount() << endl;
	os << "Player 2 Count: " << obj.GetPlayer2PieceCount() << endl;

	for(int i=0; i<BOARD_Y; i++)
	{
		for(int j=0; j<BOARD_X; j++)
		{
			os << obj.GetValue(j,i) << " ";
		}
		os << endl;
	}
	return os;
}

/*********************************************************
 * Board::operator=()
 * Overloads the assignment operator so that a board can
 * easily be copied.
 ********************************************************/
Board &Board::operator=(Board &obj)
{
	for(int i=0; i<BOARD_Y; i++)
	{
		for(int j=0; j<BOARD_X; j++)
		{
          this->SetValue(j, i, obj.GetValue(j, i));
		}
	}
    return *this;
}
